﻿using UnityEngine;
using System.Collections;

public class MusicLoop : MonoBehaviour {
	public static void Init(AudioSource target,float[] looptime,float yieldtime){
		if (target == null) {
			Debug.Log("target == null");
			return ;
		}
		MusicLoop musicloop = target.gameObject.GetComponent<MusicLoop> ();
		if (musicloop == null) {
			musicloop = target.gameObject.AddComponent<MusicLoop>();
		}
		musicloop.SetLoop(target,looptime,yieldtime);
	}
	public AudioSource Target;
	public float[] LoopTime;
	private float Length;
	public float smoothtime = 0.5f;
	public float offest = 0.1f;
	public float YieldTime;

	public FSM _state = new FSM();
	public StatePath m_Yield = new StatePath ("Yield");
	public StatePath m_Comming =new StatePath ("Comming");
	public StatePath m_Playing = new StatePath("Playing");
	public StatePath m_GoOut = new StatePath ("GoOut");
	public void SetLoop(AudioSource target,float[] looptime,float yieldtime = 0){
		YieldTime = yieldtime;
		Target = target;
		LoopTime = looptime;
		Length = LoopTime [1] - LoopTime [0];

		_state.AddState (m_Comming, OnComming, OnCommingUpdate);
		_state.AddState (m_Playing, OnPlaying, OnPlayingUpdate);
		_state.AddState (m_GoOut, OnGoOuting, OnGoOutUpdate);
		_state.AddState (m_Yield, OnYieldEnter, OnYieldUpdate);

		_state.SetState(m_Yield);
	}
	public void OnYieldEnter(){
		Target.volume = 0;
		Target.Stop ();
	}
	public void OnYieldUpdate(float dt){
		if(_state.stateTime > YieldTime)
			_state.SetState(m_Comming);
	}
	public void OnComming(){
		Target.time = LoopTime [0];
		Music.SmoothSlow (Target, 1, smoothtime-offest);
		Target.Play ();
	}
	public void OnCommingUpdate(float dt){
		if (_state.stateTime >= smoothtime)
			_state.SetState(m_Playing);
	}
	public void OnPlaying(){
	}
	public void OnPlayingUpdate(float dt){
		if (_state.stateTime >= Length - 2 * smoothtime) {
			_state.SetState(m_GoOut);
		}
	}
	public void OnGoOuting(){
		Music.SmoothSlow (Target, 0, smoothtime-offest);
	}
	public void OnGoOutUpdate(float dt){
		if (_state.stateTime >= smoothtime)
			_state.SetState(m_Comming);	
	}

	public void Update(){
		_state.UpdateState (Time.deltaTime);
	}
	public void OnDisable(){
		GameObject.Destroy (this);
	}
}
